import { h, render } from 'vue'
import { ThemeColor } from '../themes'
import notifyVue from './notify.vue'

export interface Content {
  message: string
  type: ThemeColor
  create: number
  expire: number
}

let el = null as HTMLElement | null
const contents = ref([] as Content[])

function checkExpire() {
  let index = -1
  const now = Date.now()
  for (const content of contents.value) {
    if (content.expire < now) {
      index = contents.value.indexOf(content)
      break
    }
  }
  if (index >= 0) {
    contents.value.splice(index, 1)
  }
}

setInterval(() => {
  checkExpire()
}, 200)

export function notify(content: Omit<Content, 'expire' | 'create'>) {
  if (!el) {
    el = document.createElement('div')
    el.id = 'lx-notify'
    document.body.appendChild(el)
  }
  setTimeout(() => {
    const now = Date.now()
    contents.value.push({
      ...content,
      create: now,
      expire: now + 1.5 * 1000,
    })
    const inst = h(notifyVue, { contents: contents.value })
    render(inst, el!)
  })
}

notify.primary = (message: string) => notify({ type: 'primary', message })
notify.success = (message: string) => notify({ type: 'success', message })
notify.warning = (message: string) => notify({ type: 'warning', message })
notify.danger = (message: string) => notify({ type: 'danger', message })
notify.error = (message: string) => notify({ type: 'error', message })
notify.info = (message: string) => notify({ type: 'info', message })

export function backWhenSuccess(value: boolean) {
  if (value) {
    notify.success('操作成功')
    setTimeout(() => {
      window.history.back()
    })
  }
  else {
    // notify({
    //   type: 'danger',
    //   message: '操作失败',
    // })
    notify.error('操作失败')
  }
}
